<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="gettabledata" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <template #field-messageType="scope">
          <el-select clearable @clear="gettabledata" v-model="searchFrom.messageType" placeholder="请选择消息类型"
            @change="v => scope.data.model.callback(v)">
            <el-option v-for="item in messagetypeas" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button type="primary" plain @click="redall">一键已读</el-button>
        <el-button type="danger" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button>
        <!-- <sj-button custom-type="sred" @click="deletes"  :disabled="!selectionData.length">批量删除</sj-button> -->
      </div>
      <el-table class="mt-5" border :data="tabdata.data" style="width: 100%" @selection-change="selectionChange"
        v-loading="isLoading">
        <el-table-column type="selection" width="55" fixed="left">
        </el-table-column>
        <el-table-column prop="id" show-overflow-tooltip label="编号" width="100">
        </el-table-column>
        <el-table-column prop="unityName" show-overflow-tooltip label="所属单位" min-width="100">
        </el-table-column>
        <el-table-column prop="projectName" show-overflow-tooltip label="所属项目" min-width="150">
        </el-table-column>
        <el-table-column prop="messageType" show-overflow-tooltip minWidth='100' label="消息类型">
          <template v-slot="{ row }">
            <!-- {{ isNullOrEmpty( MESSAGETYPETEXT[row.messageType]?.label ) }} -->
            {{ isNullOrEmpty(row.messageTypeName) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" show-overflow-tooltip label="消息类容" minWidth='150'>
        </el-table-column>
        <el-table-column prop="readStatus" minWidth="90" label="是否已读">
          <template v-slot="{ row }">
            <el-tag :type="row.readStatus == 1 ? 'danger' : 'info'">
              {{ isNullOrEmpty(row.readStatus == 1 ? "未读" : "已读") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="时间" width="180" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="dealView" label="操作" fixed="right" width="100">
          <template v-slot="{ row }">
            <el-space>
              <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
              <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tabdata.total" @size-change="gettabledata" @current-change="gettabledata" />
      </div>
    </RePage>
  </div>
</template>
<script setup lang="ts">
import RePage from "@/components/RePage/index.vue";
import infos from "./info.vue";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import { isNullOrEmpty } from '@/utils/functions'
import { deviceDetection, debounce } from "@pureadmin/utils";
import { PAGE_LAYOUT } from "@/constant";
import { ElMessage, ElMessageBox } from "element-plus";
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables"
import { getList, deleteMessageFun, readAllFun, getInfo, messagetype } from "@/api/operate/messagelist/index";
import { addDialog } from "@/components/ReDialog";
import { onMounted, ref } from "vue";
import { emitter } from '@/utils/mitt'

const usePagedata = usePageVariablesStoreHook()
const key = ref(0);
const messagetypeas = ref([])
const selectionData = ref([]);
const searchFrom = ref({
  page: 1,
  limit: 10,
  messageType: "",
  readStatus: "",
  projectName: ""
});
const isLoading = ref(true);
const tabdata = ref({
  total: 0,
  data: []
});
const formRef = ref()
const redstatus = ref([
  {
    value: 2,
    label: "已读"
  },
  {
    value: 1,
    label: "未读"
  }
]);
const searchFormRules = ref([
  {
    type: "fieldComponent",
    field: "messageType",
    title: "消息类型",
    value: null,
    options: messagetypeas.value,

    props: {
      placeholder: "请选择消息类型",
      clearable: true
    }
  },
  {
    type: "select",
    field: "readStatus",
    title: "是否已读",
    value: null,
    options: redstatus.value,
    props: {
      placeholder: "请选择",
      clearable: true
    }
  },
  {
    type: "input",
    field: "projectName",
    title: "项目名称",
    value: null,
    options: "",
    props: {
      placeholder: "请输入项目名称",
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
]);


onMounted(() => {
  gettabledata();
  messagetype().then(res => {
    messagetypeas.value = res.result
    key.value++
    usePagedata.messagenew += 1
  });
  emitter.on('eventsOperate', gettabledata)
});
onBeforeUnmount(()=>{
  emitter.off('eventsOperate', gettabledata)
})

const gettabledata = () => {
  getList(searchFrom.value).then(res => {
    isLoading.value = false;
    tabdata.value.data = res.result.data;
    tabdata.value.total = res.result.total;
  });
};
const selectionChange = data => {
  selectionData.value = data;
};
function changemessage() {
  usePagedata.messagenew += 1
}
const defaultInfoForm = () => {
  return {
    id: null, // id
    messageType: null, // projectName
    content: null, // missionName
    readStatus: null, // missionStatus
    createdAt: null, // cycleValue
    nickname: null, // finishDate
  };
};
// 详情
const info = row => {
  changemessage()
  addDialog({
    title: `消息详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        taskId: row.id,
        formInline: defaultInfoForm()
      };
      getInfo({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            usePagedata.messagenew += 1
            options.props.formInline = res.result;
            gettabledata()
          }
        })
        .finally(() => {
          options.props.isLoading = false;
          usePagedata.messagenew += 1
        });
    }
  });
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteMessageFun({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        changemessage()
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        gettabledata();
      }
    });
  });
};
const defaultSearchFrom = () => {
  return {
    messageType: null,
    readStatus: null,
    projectName: null,
    page: 1,
    limit: 10
  };
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchFrom.value, defaultSearchFrom());
  key.value++;
  gettabledata();
};
const redall = () => {
  readAllFun().then(res => {
    if (res.code === 200) {
      gettabledata();
      changemessage()
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const DebounceGetTableList = debounce(gettabledata, 1000, true);
const DebounceResetting = debounce(resetting, 1000, true);
</script>
